package com.kukudexin.safety;

/**
 * @author: 酷酷的鑫
 * @description:
 */
public class DeadlockThread implements Runnable{
    private int count = 1;
    private String lock = "lock";

    /**
     * 代码分析  thread0 --- A     thread1 --- B count=2时
     * A线程执行 a方法，某一个时间点 count被B线程改成奇数此时A线程判断余数不为0走b方法。同理B 线程也可以走a，b方法
     */
    @Override
    public void run() {
        while (true) {
            count++;
            if (count % 2 == 0) {
                synchronized (lock) {
                    a();
                }
            } else {
                synchronized (this) {
                    b();
                }
            }
        }
    }

    private void b() {
        System.out.println(Thread.currentThread().getName() + ",b方法...");
    }

    private void a() {
        System.out.println(Thread.currentThread().getName() + ",a方法...");
    }

    public static void main(String[] args) {
        DeadlockThread deadlockThread = new DeadlockThread();
        Thread thread1 = new Thread(deadlockThread);
        Thread thread2 = new Thread(deadlockThread);
        thread1.start();
        thread2.start();
    }
}
